/**
 * 奖励条款规则 列表页
 *
 * 作者 zjb
 * 日期 2024-08-30 09:51:15
 */
layui.use(['jquery', 'laydate', 'febs', 'form', 'table', 'commonJS', 'validate'], function () {
    var $ = layui.jquery,
        laydate = layui.laydate,
        febs = layui.febs,
        form = layui.form,
        table = layui.table,
        commonJS = layui.commonJS,
        validate = layui.validate,
        $view = $('#febs-incentiveRewardClauseRule'),
        $query = $view.find('#query'),
        $searchForm = $view.find('#incentiveRewardClauseRule-table-form'),
        tableIns,
        leftTableIns,
        rightTableIns;

    let incentiveRewardClauseRuleTableQueryParams = {
        tenantId: null,
        clauseId: null,
        clauseName: null,
        clauseNo: null,
        status: null,
        clauseContent: null
    };

    // function initParam() {
    //     incentiveRewardClauseRuleTableQueryParams.tenantId = ""
    //     incentiveRewardClauseRuleTableQueryParams.clauseId = ""
    //     incentiveRewardClauseRuleTableQueryParams.clauseName = ""
    //     incentiveRewardClauseRuleTableQueryParams.clauseNo = ""
    //     incentiveRewardClauseRuleTableQueryParams.status = ""
    // }
    form.verify(validate);
    form.render();

    $view.find('#selectIncentiveRewardClause').on("click", function () {
        febs.modal.open('选择奖励条款', 'common/incentiveRewardClause', {
            btn: ['确认', '关闭'],
            area: $(window).width() <= 750 ? ['95%', '85%'] : ['70%', '85%'],
            yes: function (index, layero) {
                getSelectData();
                layer.close(index);
            },
            btn2: function (index, layero) {
                layer.close(index);
                return false;
            }
        });
    })

    initTable();

    function initTable() {
        initLeftTable();
    }

    $query.on('click', function () {
        //重载左侧表格
        leftTableIns.reload({where: getQueryParams(), page: {curr: 1}});
    });

    table.on('tool(incentiveRewardClauseTable)', function (obj) {
        //表格编辑删除事件
        var id = obj.data.clauseId;
        var layEvent = obj.event;
        if (layEvent === 'edit') {
            febs.modal.open('修改奖励条款类型', 'incentiveRewardClause/update/' + id, {
                btn: ['提交', '取消'],
                area: [$(window).width() <= 750 ? '90%' : '600px', '350px'],
                yes: function (index, layero) {
                    $('#incentiveRewardClause-edit').find('#submit').trigger('click');
                },
                btn2: function () {
                    layer.closeAll();
                },
            });
            $view.find('#ruleQuery').trigger('click');
        } else if (layEvent === 'del') {
            febs.modal.confirm('删除条款', '确定删除所选条款？', function () {
                deleteIds(id);
                $query.trigger('click');
            });
        }

    });

    table.on('toolbar(incentiveRewardClauseTable)', function (obj) {
        if (obj.event === 'add') {
            febs.modal.open('新增奖励条款类型', 'incentiveRewardClause/add', {
                btn: ['提交','取消'],
                area: [$(window).width() <= 750 ? '90%' : '600px', '350px'],
                yes: function (index, layero) {
                    $('#incentiveRewardClause-edit').find('#submit').trigger('click');
                },
                data: {
                    tenantId: $searchForm.find('select[name="tenantId"]').val()
                }
            });
        }
    });

    table.on('tool(incentiveRewardClauseRuleTable)', function (obj) {
        //表格编辑删除事件
        var id = obj.data.clauseRuleId;
        var layEvent = obj.event;
        if (layEvent === 'edit') {
            febs.modal.open('修改条款类型规则', 'incentiveRewardClauseRule/update/' + id, {
                btn: ['提交', '取消'],
                area: [$(window).width() <= 750 ? '90%' : '50%', "550px"],
                yes: function (index, layero) {
                    $('#incentiveRewardClauseRule-edit').find('#submit').trigger('click');
                },
                btn2: function () {
                    layer.closeAll();
                },
            });
            $view.find('#ruleQuery').trigger('click');
        } else if (layEvent === 'del') {
            febs.modal.confirm('删除条款', '确定删除所选条款？', function () {
                deleteRuleIds(id);
                $view.find('#ruleQuery').trigger('click');
            });
        }

    });

    table.on('toolbar(incentiveRewardClauseRuleTable)', function (obj) {
        if (obj.event === 'ruleQuery') {
            queryIncentiveRewardClauseRule(obj)
        } else if (obj.event === 'ruleAdd') {
            addIncentiveRewardClauseRule(obj)
        }
    });

    form.on('switch(statusOption)', function (obj) {
        //奖品状态控制点击事件
        var checked = obj.elem.checked;
        var status;
        if (checked) {
            status = "1";
        } else {
            status = "0";
        }
        //获取该控件所在行
        var index = obj.othis.parents('tr').eq(0).data('index');
        //获取表中所有数据 按行取数据及其id
        var id = table.cache['incentiveRewardClauseTable'][index].clauseId;

        febs.modal.confirm('更改条款状态', '确认更改条款状态', function () {
            updateStatus(id, status);
        }, function () {
            obj.elem.checked = !checked;
            layer.closeAll();
            form.render('checkbox');
        });

    });

    function updateStatus(id, status) {
        //更新奖品状态
        let model = {
            clauseId: id,
            status: status
        }
        febs.postArray(ctx + 'incentiveRewardClause/updateStatus', model, function () {
            febs.alert.success('修改条款状态成功');
        })
    }
    form.on('switch(statusOptionRule)', function (obj) {
        //奖品状态控制点击事件
        var checked = obj.elem.checked;
        var status;
        if (checked) {
            status = "1";
        } else {
            status = "0";
        }
        //获取该控件所在行
        var index = obj.othis.parents('tr').eq(0).data('index');
        //获取表中所有数据 按行取数据及其id
        var id = table.cache['incentiveRewardClauseRuleTable'][index].clauseRuleId;

        febs.modal.confirm('更改奖励状态', '确认更改奖励状态', function () {
            updateRuleStatus(id, status);
        }, function () {
            obj.elem.checked = !checked;
            layer.closeAll();
            form.render('checkbox');
        });

    });

    function updateRuleStatus(id, status) {
        //更新奖品状态
        let model = {
            clauseRuleId: id,
            status: status
        }
        febs.postArray(ctx + 'incentiveRewardClauseRule/updateStatus', model, function () {
            febs.alert.success('修改奖励状态成功');
        })
    }

    function getQueryParams() {
        return {
            tenantId: $searchForm.find('select[name="tenantId"]').val(),
            status: $searchForm.find("select[name='status']").find("option:selected").val(),
            useScope: $searchForm.find("select[name='useScope']").find("option:selected").val(),
            clauseName: $searchForm.find("input[name='clauseName']").val(),
            invalidate_ie_cache: new Date()
        };
    }

    table.on('row(incentiveRewardClauseTable)', function (obj) {
        obj.tr.addClass('layui-bg-green').siblings().removeClass('layui-bg-green');
        incentiveRewardClauseRuleTableQueryParams.tenantId = obj.data.tenantId
        incentiveRewardClauseRuleTableQueryParams.clauseId = obj.data.clauseId
        incentiveRewardClauseRuleTableQueryParams.clauseName = obj.data.clauseName
        incentiveRewardClauseRuleTableQueryParams.clauseNo = obj.data.clauseNo
        incentiveRewardClauseRuleTableQueryParams.status = $view.find("select[name='ruleStatus']").find("option:selected").val();
        initRightTable();
    });

    // 主表数据
    function initLeftTable() {
        leftTableIns = febs.table.init({
            elem: $view.find('table[name="incentiveRewardClauseTable"]'),
            id: 'incentiveRewardClauseTable',
            url: ctx + 'incentiveRewardClause/list',
            where: getQueryParams(),
            height: getTableHeight(),
            skin: '',
            cols: [[
                {type: 'numbers', width: 60, title: '序号'},
                {field: 'clauseId', title: 'id', minWidth: 120, hide: true},
                {field: 'tenantId', title: '公司ID', minWidth: 120, hide: true},
                {field: 'clauseName', title: '条款名称', minWidth: 120},
                {
                    field: 'useScope', title: '适用范围', align: 'center', width: 90, templet: function (d) {
                        if (d.useScope == '1') {
                            return '<span class="layui-badge febs-tag-cyan">本工</span>'
                        } else if (d.useScope == '2') {
                            return '<span class="layui-badge febs-tag-orange">外包</span>'
                        } else if(d.useScope == '3'){
                             return  '<span class="layui-badge febs-tag-green">外协</span>'
                        } else if(d.useScope == '4'){
                             return  '<span class="layui-badge febs-tag-geekblue">承包队</span>'
                        } else if(d.useScope == '10'){
                            return  '<span class="layui-badge febs-bg-blue">全部</span>'
                        }
                    }
                },
                {field: 'sort', title: '排序', align: 'center', width: 40},
                {field: 'status', title: '状态', toolbar: '#statusOption', align: 'center', width: 95},
                {title: '操作', toolbar: '#incentiveRewardClause-tool', align: 'center', width: 100, fixed: 'right'}

            ]],
            toolbar: '#incentiveRewardClause-toolbar',
            defaultToolbar: [],
            done: function (res, curr, count) {
                if (res && res.count > 0) {
                    $view.find(".layui-table-view[lay-table-id='incentiveRewardClauseTable'] .layui-table-body.layui-table-main tr[data-index=0]").click();
                } else {
                    // initParam()
                    incentiveRewardClauseRuleTableQueryParams.tenantId = $searchForm.find('select[name="tenantId"]').val()
                    incentiveRewardClauseRuleTableQueryParams.status = $searchForm.find("select[name='status']").find("option:selected").val()
                    incentiveRewardClauseRuleTableQueryParams.useScope = $searchForm.find("select[name='useScope']").find("option:selected").val()
                    initRightTable()
                    $view.find('#ruleAdd').attr("disabled", true).addClass("layui-btn-disabled");
                    $view.find('#ruleQuery').attr("disabled", true).addClass("layui-btn-disabled");
                }
            }
        });
    }

    // 子表数据
    function initRightTable() {
        rightTableIns = febs.table.init({
            elem: $view.find('table[name="incentiveRewardClauseRuleTable"]'),
            id: 'incentiveRewardClauseRuleTable',
            height: getTableHeight(),
            skin: '',
            where: incentiveRewardClauseRuleTableQueryParams,
            url: ctx + 'incentiveRewardClauseRule/list',
            cols: [[
                {type: 'numbers', width: 60, title: '序号'},
                {field: 'clauseRuleId', title: 'id', minWidth: 120, hide: true},
                {field: 'tenantId', title: '公司ID', minWidth: 120, hide: true},
                {field: 'clauseId', title: '违章条款Id', minWidth: 120, hide: true},
                {field: 'clauseNo', title: '条款编号', width: 120},
                {field: 'clauseLevel', title: '条款等级', width: 100, align: 'center'},
                {field: 'referenceMoney', title: '奖励金额', width: 120, align: 'center'},
                {field: 'examineScore', title: '考核分数', width: 120, align: 'center'},
                {field: 'clauseContent', title: '条款内容', minWidth: 120},
                {field: 'executeDate', title: '执行时间', width: 170, align: 'center',templet:function (d) {
                        if(d.executeDate){
                            return d.executeDate.substring(0,10)
                        }
                    }},
                {field: 'status', title: '状态', toolbar: '#statusOptionRule', align: 'center', width: 120},
                {
                    title: '操作',
                    toolbar: '#incentiveRewardClauseRule-option',
                    align: 'center',
                    width: 120,
                    fixed: 'right'
                }
            ]],
            toolbar: '#incentiveRewardClauseRule-toolbar',
            defaultToolbar: [],
            done: function (res, curr, count) {
                if (!commonJS.isEmpty(incentiveRewardClauseRuleTableQueryParams.clauseNo)) {
                    $view.find('input[name="clauseNo"]').val(incentiveRewardClauseRuleTableQueryParams.clauseNo)
                }
                // if(!commonJS.isEmpty(incentiveRewardClauseRuleTableQueryParams.status)){
                //     $view.find('input[name="clauseNo"]').val(incentiveRewardClauseRuleTableQueryParams.clauseNo)
                // }
            }
        });
    }

    function queryIncentiveRewardClauseRule(obj) {
        if (!commonJS.isEmpty(incentiveRewardClauseRuleTableQueryParams.clauseId)) {
            incentiveRewardClauseRuleTableQueryParams.clauseNo = $view.find('input[name="clauseNo"]').val();
            incentiveRewardClauseRuleTableQueryParams.clauseContent = $view.find('input[name="clauseContent"]').val();
            incentiveRewardClauseRuleTableQueryParams.status = $view.find("select[name='ruleStatus']").find("option:selected").val();
            //重载右侧承包队表
            initRightTable();
        } else {
            febs.alert.error('未选中条款类型。');

        }
    }

    function addIncentiveRewardClauseRule(obj) {
        if (!commonJS.isEmpty(incentiveRewardClauseRuleTableQueryParams.clauseId)) {
            incentiveRewardClauseRuleTableQueryParams.clauseNo = $view.find('input[name="clauseNo"]').val();
            incentiveRewardClauseRuleTableQueryParams.clauseContent = $view.find('input[name="clauseContent"]').val();
            incentiveRewardClauseRuleTableQueryParams.status = $view.find("select[name='ruleStatus']").find("option:selected").val();
            //重载右侧承包队表
            initRightTable();
        } else {
            febs.alert.error('未选中条款类型。');
            return;
        }
        febs.modal.open('新增条款类型规则', 'incentiveRewardClauseRule/add', {
            btn: ['提交', '取消'],
            area: [$(window).width() <= 750 ? '90%' : '50%', "550px"],
            yes: function (index, layero) {
                $('#incentiveRewardClauseRule-edit').find('#submit').trigger('click');
            },
            data: {
                tenantId: incentiveRewardClauseRuleTableQueryParams.tenantId,
                clauseId: incentiveRewardClauseRuleTableQueryParams.clauseId,
                clauseName: incentiveRewardClauseRuleTableQueryParams.clauseName
            }
        });
    }

    table.on('sort(incentiveRewardClauseRuleTable)', function (obj) {
        tableIns.reload({
            initSort: obj,
            where: $.extend(getQueryParams(), {
                field: obj.field,
                order: obj.type
            }),
            autoSort: true
        });
    });

    function reloadPage(curr) {
        var _curr = $view.find(".layui-laypage-em").next().html();
        if (!!curr) {
            _curr = curr;
        }
        leftTableIns.reload({where: getQueryParams(), page: {curr: _curr}});
    }

    $query.on('click', function () {
        reloadPage(1);
    });

    table.on('toolbar(incentiveRewardClauseRuleTable)', function (obj) {
        if (obj.event === 'ruleQuery') {
            queryIncentiveRewardClauseRule(obj)
        } else if (obj.event === 'ruleAdd') {
            addIncentiveRewardClauseRule(obj)
        }
    });

    table.on('tool(baseProjectTable)', function (obj) {
        var data = obj.data,
            layEvent = obj.event;
        if (layEvent === 'del') {
            febs.modal.confirm('删除数据', '确定删除所选数据？', function () {
                deleteIds(data.clauseRuleId);
            });
        }
        if (layEvent === 'edit') {
            febs.modal.open('修改', 'incentiveRewardClauseRule/update/' + data.projectId, {
                area: [$(window).width() <= 750 ? '95%' : '50', '800px'],
                btn: ['提交', '取消'],
                yes: function (index, layero) {
                    $('#incentiveRewardClauseRule-edit').find('#submit').trigger('click');
                },
                btn2: function () {
                    layer.closeAll();
                },
                data: {},
            });
        }
    });


    function deleteIds(ids) {
        febs.get(ctx + 'incentiveRewardClause/delete/' + ids, null, function () {
            febs.alert.success('删除数据成功');
            $query.trigger('click');
        });
    }
    function deleteRuleIds(ids) {
        febs.get(ctx + 'incentiveRewardClauseRule/delete/' + ids, null, function () {
            febs.alert.success('删除数据成功');
            $query.trigger('click');
        })
    }

    function getTableHeight() {
        return commonJS.calcTableHeight();
    }

    $(window).resize(function () {
        leftTableIns.reload({height: getTableHeight()});
        rightTableIns.reload({height: getTableHeight()});
    });

});